package leetcode.other.p25;
class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}

class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        int n = 0;
        ListNode cur = head;
        while (cur != null) {
            n++;
            cur = cur.next;
        }
        ListNode dummyNode = new ListNode(-1, head);
        ListNode p0 = dummyNode;
        cur = head;
        for (int i = 0; i < n / k; i++) {
            ListNode pre = null;
            ListNode next = null;
            cur = p0.next;
            for (int j = 0; j < k; j++) {
                next = cur.next;
                cur.next = pre;
                pre = cur;
                cur = next;
            }
            ListNode p1 = p0.next;
            p0.next.next = cur;
            p0.next = pre;
            p0 = p1;
        }

        return dummyNode.next;
    }
}